/**  
 * @Title: MetaService.java
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-05-05 09:04:26 
 */  
package com.fsxgt.datagrid.ds.service.impl;

import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutionException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

import com.fsxgt.datagrid.ds.bo.ColumnInfo;
import com.fsxgt.datagrid.ds.bo.DatasourceJdbcBO;
import com.fsxgt.datagrid.ds.component.QueryComponent;
import com.fsxgt.datagrid.ds.exception.DsException;
import com.fsxgt.datagrid.ds.handler.DbHandler;
import com.fsxgt.datagrid.ds.utils.JsqlparserUtil;
import com.fsxgt.datagrid.ds.utils.ParamUtil;

import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.select.PlainSelect;
import net.sf.jsqlparser.statement.select.Select;

/**  
 * @ClassName: MetaService
 * @Description: TODO(描述)
 * @author liuyi
 * @date 2023-05-05 09:04:26 
*/
@Service
public class MetaService {

	@Autowired
	private QueryComponent queryComponent;
	@Autowired
	private DatasourceJdbcService datasourceJdbcService;
	
	
	public List<String> findTableNames(DatasourceJdbcBO bo,String schema) throws  Exception {

	
	
		DbHandler dbHandler = getQuerySqlHandler(bo);
		List<String> tableNames= null;
		
		tableNames=dbHandler.getTableNames(schema);
		
		return tableNames;
		
	}
	
	
	public List<String> findSchemas(DatasourceJdbcBO bo) throws  DsException, SQLException {


		DbHandler dbHandler = getQuerySqlHandler(bo);
		
		return dbHandler.getSchemas();
		
	}
	
	private DbHandler getQuerySqlHandler(DatasourceJdbcBO bo) throws  DsException {
		DbHandler dbHandler = queryComponent.getHandler(bo.getId());
		return dbHandler;
	}
	

	
	public List<ColumnInfo> findColumnNames(DatasourceJdbcBO bo,String schema,String tableName) throws  Exception {

		
	
		DbHandler dbHandler = getQuerySqlHandler(bo);
		
		List<ColumnInfo> columns = dbHandler.getColumnNames(schema,tableName);
		
		return columns;
		
	}
	
	public List<ColumnInfo> findColumnNamesForSql(DatasourceJdbcBO bo,String sqlText) throws Exception   {

		DbHandler dbHandler = getQuerySqlHandler(bo);

		


        sqlText=JsqlparserUtil.removeWhere(sqlText, " 1=2 ");
        
	
		return dbHandler.getColumnsBySql(sqlText);
		
	}


	
}
